var $;
var layer;

const identity = 'ADMIN';
const secret = 'LhjKGNF86ZPCRFrmJvpEyKgJ8MP5GMHvUlfYX678HXLJOUAZE9siNimfE4wXIWK4';
const version= '1.0.0';
const device= '0000-0000-1111-1111';

const domain = window.location.protocol+"//"+window.location.host;
const api_domain = domain+'/app/admin/';

const request_option = {
    'tip':true,
    'async':true,
    'method':'get'
};

var response_data;

const is_sign = true;


const now = new Date();
const year = now.getFullYear();
const month = ('0' + (now.getMonth() + 1)).slice(-2);
const day = ('0' + now.getDate()).slice(-2);

const dateKey = year+'-'+month+'-'+day;
const date_today_mark = {[dateKey]:'今天'};

function request_data(url,params,option,callback)
{
    try {

        params = params ? params : {};
        var param = get_params(params);

        option = typeof option=='object' ? option : {};
        var method =  option.hasOwnProperty('method') ? option.method:request_option.method;
        var tip = option.hasOwnProperty('tip') ? option.tip:request_option.tip;
        var async = option.hasOwnProperty('async') ? option.async: request_option.async;

        //加入等待状态，只有同步下，才可以看出效果
        if(typeof layer!='undefined'){
            layer.load();
        }

        $.ajax({
                url:api_domain+url,
                dataType:'json',
                data:param,
                async:async,
                timeout:30000,
                type:method,
                headers:get_header(param),
                beforeSend: function (XMLHttpRequest) {
                    //XMLHttpRequest.setRequestHeader("token", localStorage.getItem('token'));
                },
                complete:function(xhr,status){
                    if(typeof layer!='undefined'){
                        layer.closeAll('loading');
                    }
                },
                error:function(xhr,status,errorThrown){
                    if(typeof layer!='undefined'){
                        layer.msg('请求异常');
                    }else{
                        alert('请求异常');
                    }
                },
                success:function(response,status){
                    response_data = response.result;

                    if(response.code!=0){
                        if(response.code==1000) {
                            if(typeof layer!='undefined'){
                                layer.msg('未登录');
                            }else{
                                alert('未登录');
                            }

                            location.href='/app/admin/login/index'
                        }else{
                            if(tip===true){
                                if(typeof layer!='undefined'){
                                    layer.msg(response.msg,{time:2000,icon: 2});
                                }else if(typeof parent.layer!='undefined'){
                                    parent.layer.msg(response.msg,{time:2000,icon: 2});
                                }else{
                                    alert(response.msg);
                                }
                            }
                        }
                    }else{
                        if(typeof callback === "function"){
                            callback(response);
                        }
                        // if(response_data.hasOwnProperty('token') && response.result.token!=false){
                        //     //deletes('token');
                        //     //cookie_set("token",response.result.token,1);
                        //     //cookie_set("empl_info",JSON.stringify(response.result.empl_info),1);
                        // }

                    }
                }
            }
        );

        return response_data;

    } catch(err) {

        console.log(err);

    }

}

function get_header(param) {
    var header = {
        "uuid":'admin1234567890',
        "token": localStorage.getItem('token')||'',
        "platform": identity,
        "version": version,
        "device": device,
        "time":parseInt(new Date().getTime()/1000),
        "random":Math.random()
    };
    header.voucher = gen_sign(header,param);
    return header;
}

function get_params(params) {
    if (typeof params == "object") {
        //console.log(params);
        return params;
    }else if(typeof params == 'string' && params!=false){
        if(typeof layer!='undefined'){
            return layer.msg('参数必须是对象类型');
        }else{
            return alert('参数必须是对象类型');
        }
    }
}

function gen_sign(header, params) {
    //todo 1头部签名
    var keys = [];
    for (var i in header) {
        if(i!='voucher'){
            keys.push(i);
        }
    }
    keys = keys.sort();

    var str = '';
    for (var i in keys){
        var k = keys[i];
        if(k in header &&  header[k]!==undefined && k!='sign' && k!='file' && k!='page' && k!='limit'){
            if(header[k] instanceof Array){
                str += k+'=array{{ANYUE}}';
            }else if(header[k] instanceof Object){
                str += k+'=object{{ANYUE}}';
            }else if(header[k]===''){
                str += k+'=false{{ANYUE}}';
            }else {
                str += k+'='+header[k]+'{{ANYUE}}';
            }
        }
    }

    var string1 = hex_md5(hex_md5(str)+hex_md5(secret));

    //todo 2参数签名
    var keys = [];
    for (var i in params) {
        keys.push(i);
    }
    keys = keys.sort();

    var str = '';
    for (var i in keys){
        var k = keys[i];
        if(k in params &&  params[k]!==undefined && k!='s' && k!='file' && k!='__file__' && k!='page' && k!='limit' && k!='field' && k!='order'){
            //如果是空数组或者空对象，没有传参数，所以要过滤掉
            if(params[k] instanceof Array && params[k].length==0){
                continue;
            }
            if(params[k] instanceof Object && params[k].length==0){
                continue;
            }

            if((params[k] instanceof Array)){
                str += k+'=array{{ANYUE}}';
            }else if(params[k] instanceof Object){
                if(typeof params[k][0]!="undefined"){
                    str += k+'=array{{ANYUE}}';
                }else{
                    str += k+'=object{{ANYUE}}';
                }
            }else if(params[k]==='' ){
                str += k+'=false{{ANYUE}}';
            }else {
                var string =  params[k].toString();
                //去掉右边空格
                //string = string.replace(/(\s*$)/g,'');
                str += k+'='+string+'{{ANYUE}}';
            }
        }
    }
    //console.log(str);
    var string2 = hex_md5(hex_md5(str)+hex_md5(secret));


    return string1+string2;
}

function cookie_set(key,val,time) {
    var date=new Date(); //获取当前时间
    var expiresDays=time;  //将date设置为n天以后的时间
    date.setTime(date.getTime()+expiresDays*24*3600*1000); //格式化为cookie识别的时间
    document.cookie=key + "=" + val +";expires="+date.toGMTString()+";path=/";  //设置cookie
}

function cookie_get(key) {
    /*获取cookie参数*/
    var getCookie = document.cookie.replace(/[ ]/g,"");  //获取cookie，并且将获得的cookie格式化，去掉空格字符
    var arrCookie = getCookie.split(";")  //将获得的cookie以"分号"为标识 将cookie保存到arrCookie的数组中
    var tips='';  //声明变量tips
    for(var i=0;i<arrCookie.length;i++){   //使用for循环查找cookie中的tips变量
        var arr=arrCookie[i].split("=");   //将单条cookie用"等号"为标识，将单条cookie保存为arr数组
        if(key==arr[0]){  //匹配变量名称，其中arr[0]是指的cookie名称，如果该条变量为tips则执行判断语句中的赋值操作
            tips=arr[1];   //将cookie的值赋给变量tips
            break;   //终止for循环遍历
        }
    }
    return tips;
}

function deletes(key) {
    var date = new Date(); //获取当前时间
    date.setTime(date.getTime()-10000); //将date设置为过去的时间
    document.cookie = key + "=v; expires =" +date.toGMTString();//设置cookie
}

function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var urlArr = window.location.href.split('#');
    var queryParam = urlArr[1].split('?');
    if(queryParam[1]){
        var r = queryParam[1].match(reg); //获取url中"?"符后的字符串并正则匹配
        var context = "";
        if (r != null)
            context = r[2];
        reg = null;
        r = null;
        return context == null || context == "" || context == "undefined" ? "" : context;
    }else{
        return null;
    }

}

function isMobile() {
    if(/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)) {
        return true;
    } else {
        return false;
    }
}

//加密
function compile(code) {
    var c=String.fromCharCode(code.charCodeAt(0)+code.length);
    for(var i=1;i<code.length;i++){
        c+=String.fromCharCode(code.charCodeAt(i)+code.charCodeAt(i-1));
    }
    return(escape(c));
}

//解密
function uncompile(code) {
    code=unescape(code);
    var c=String.fromCharCode(code.charCodeAt(0)-code.length);
    for(var i=1;i<code.length;i++){
        c+=String.fromCharCode(code.charCodeAt(i)-c.charCodeAt(i-1));
    }
    return c;
}

function upload_file(uploads,elem,callback) {
    var path = $('#'+elem).data('path') || '';
    var name = $('#'+elem).data('filename') || '';
    var param = get_params({"path":path,"name":name});
    var request_param = '';
    $.each(param,function (i,v) {
        request_param +=i+'='+v+'&';
    });
    request_param += 's=1';

    //执行实例
    uploads.render({
        elem: '#'+elem //绑定元素
        ,accept:'file'
        ,url: api_domain + 'front/index/uploadfile?'+request_param //上传接口
        ,headers:get_header(param)
        ,before:function () {
            //layer.load(); //上传loading
            layer.load(1, {
                shade: [0.1,'#fff']
            });
        }
        ,done: function(res){
            layer.closeAll('loading'); //关闭loading

            //上传完毕回调
            if(res.code!=200){
                if (res.code == 1000) {
                    layer.msg('未登录');
                    location.href = '/login.html';
                } else {
                    layer.msg(res.msg,{time:1000,icon: 2});
                }
                return false;
            }

            if(typeof callback === "function"){
                callback(res,elem);
            }else{
                $('.'+elem+'_parent').show();
                $('.'+elem+'').text(res.result.src);
                //$('.'+elem+'_a').attr('href',res.result.src);
                $('input[name="'+elem+'"]').val(res.result.src);
            }
        }
        ,error: function(){
            layer.closeAll('loading'); //关闭loading

            //请求异常回调
            layer.msg('上传失败',{time:1000,icon: 2});
        }
    });
}

function upload_image(uploads,elem,callback) {
    var path = $('#'+elem).data('path') || '';
    var name = $('#'+elem).data('filename') || '';
    var param = get_params({"path":path,"name":name});
    var request_param = '';
    $.each(param,function (i,v) {
        request_param +=i+'='+v+'&';
    });
    request_param += 's=1';

    //执行实例
    uploads.render({
        elem: '#'+elem //绑定元素
        ,accept:'images'
        ,exts:'jpg|png|gif|bmp|jpeg'
        ,url: api_domain + 'front/index/uploadimage?'+request_param //上传接口
        ,headers:get_header(param)
        ,before:function () {
            //layer.load(); //上传loading
            layer.load(1, {
                shade: [0.1,'#fff']
            });
        }
        ,done: function(res){
            layer.closeAll('loading'); //关闭loading

            //上传完毕回调
            if(res.code!=200){
                if (res.code == 1000) {
                    layer.msg('未登录');
                    location.href = '/login.html';
                } else {
                    layer.msg(res.msg,{time:1000,icon: 2});
                }
                return false;
            }

            if(typeof callback === "function"){
                callback(res,elem);
            }else{
                $('.'+elem+'_parent').show();
                $('.'+elem+'').attr('src',res.result.src);
                //$('.'+elem+'_a').attr('href',res.result.src);
                $('input[name="'+elem+'"]').val(res.result.src);
            }
        }
        ,error: function(){
            layer.closeAll('loading'); //关闭loading

            //请求异常回调
            layer.msg('上传失败',{time:1000,icon: 2});
        }
    });
}

function upload_voice(uploads,elem,callback) {
    var path = $('#'+elem).data('path') || '';
    var name = $('#'+elem).data('filename') || '';
    var param = get_params({"path":path,"name":name});
    var request_param = '';
    $.each(param,function (i,v) {
        request_param +=i+'='+v+'&';
    });
    request_param += 's=1';

    //执行实例
    uploads.render({
        elem: '#'+elem //绑定元素
        ,accept:'audio'
        ,exts:'MP3|mp3|wav|WAV'
        ,url: api_domain + 'front/index/uploadvoice?'+request_param //上传接口
        ,headers:get_header(param)
        ,before:function () {
            //layer.load(); //上传loading
            layer.load(1, {
                shade: [0.1,'#fff']
            });
        }
        ,done: function(res){
            layer.closeAll('loading'); //关闭loading

            //上传完毕回调
            if(res.code!=200){
                if (res.code == 1000) {
                    layer.msg('未登录');
                    location.href = '/login.html';
                } else {
                    layer.msg(res.msg,{time:1000,icon: 2});
                }
                return false;
            }

            if(typeof callback === "function"){
                callback(res,elem);
            }else{
                $('.'+elem+'_parent').show();
                $('.'+elem+'').attr('src',res.result.src);
                //$('.'+elem+'_a').attr('href',res.result.src);
                $('input[name="'+elem+'"]').val(res.result.src);
            }
        }
        ,error: function(){
            layer.closeAll('loading'); //关闭loading

            //请求异常回调
            layer.msg('上传失败',{time:1000,icon: 2});
        }
    });
}

function upload_video(uploads,elem,callback) {
    var path = $('#'+elem).data('path') || '';
    var name = $('#'+elem).data('filename') || '';
    var param = get_params({"path":path,"name":name});
    var request_param = '';
    $.each(param,function (i,v) {
        request_param +=i+'='+v+'&';
    });
    request_param += 's=1';

    //执行实例
    uploads.render({
        elem: '#'+elem //绑定元素
        ,accept:'video'
        ,exts:'mp4|MP4|avi|AVI|MOV|mov|svga|SVGA'
        ,url: api_domain + 'front/index/uploadvideo?'+request_param //上传接口
        ,headers:get_header(param)
        ,before:function () {
            //layer.load(); //上传loading
            layer.load(1, {
                shade: [0.1,'#fff']
            });
        }
        ,done: function(res){
            layer.closeAll('loading'); //关闭loading

            //上传完毕回调
            if(res.code!=200){
                if (res.code == 1000) {
                    layer.msg('未登录');
                    location.href = '/login.html';
                } else {
                    layer.msg(res.msg,{time:1000,icon: 2});
                }
                return false;
            }

            if(typeof callback === "function"){
                callback(res,elem);
            }else{
                $('.'+elem+'_parent').show();
                $('.'+elem+'').data('video',res.result.src);
                //$('.'+elem+'_a').attr('href',res.result.src);
                $('input[name="'+elem+'"]').val(res.result.src);
            }
        }
        ,error: function(){
            layer.closeAll('loading'); //关闭loading

            //请求异常回调
            layer.msg('上传失败',{time:1000,icon: 2});
        }
    });
}

function batch_upload_image(uploads,elem,callback) {
    var path = $('#'+elem).data('path') || '';
    var param = get_params({"path":path});
    var request_param = '';
    $.each(param,function (i,v) {
        request_param +=i+'='+v+'&';
    });
    request_param += 's=1';

    var images = [];
    //执行实例
    uploads.render({
        elem: '#'+elem //绑定元素
        ,accept:'images'
        ,multiple: true
        ,url: '/app/admin/upload/image?'+request_param //上传接口
        ,headers:get_header(param)
        ,before:function () {
            //layer.load(); //上传loading
            layer.load(1, {
                shade: [0.1,'#fff']
            });
        },allDone: function(obj){ //当文件全部被提交后，才触发
            layer.closeAll('loading'); //关闭loading

            if(typeof callback === "function"){
                callback(images,elem);
            }
            images = [];

        },done: function(res, index, upload){ //每个文件提交一次触发一次。详见“请求成功的回调”
            //上传完毕回调
            if(res.code){
                if (res.code == 1000) {
                    layer.msg('未登录');
                    location.href = '/login.html';
                } else {
                    layer.msg(res.msg,{time:1000,icon: 2});
                }

                return false;
            }
            images.push(res.data);

        },error: function(){
            layer.closeAll('loading'); //关闭loading

            //请求异常回调
            layer.msg('上传失败',{time:1000,icon: 2});
        }
    });
}

function batch_upload_video(uploads,elem,callback) {
    var path = $('#'+elem).data('path') || '';
    var param = get_params({"path":path});
    var request_param = '';
    $.each(param,function (i,v) {
        request_param +=i+'='+v+'&';
    });
    request_param += 's=1';

    var videos = [];
    //执行实例
    uploads.render({
        elem: '#'+elem //绑定元素
        ,accept:'video'
        ,exts:'mp4|MP4|avi|AVI|MOV|mov|svga|SVGA'
        ,multiple: true
        ,url: '/app/admin/upload/video?'+request_param //上传接口
        ,headers:get_header(param)
        ,before:function () {
            //layer.load(); //上传loading
            layer.load(1, {
                shade: [0.1,'#fff']
            });
        },allDone: function(obj){ //当文件全部被提交后，才触发
            layer.closeAll('loading'); //关闭loading

            if(typeof callback === "function"){
                callback(videos,elem);
            }
            videos = [];

        },done: function(res, index, upload){ //每个文件提交一次触发一次。详见“请求成功的回调”
            //上传完毕回调
            if(res.code){
                if (res.code == 1000) {
                    layer.msg('未登录');
                    location.href = '/login.html';
                } else {
                    layer.msg(res.msg,{time:1000,icon: 2});
                }

                return false;
            }
            videos.push(res.data);

        },error: function(){
            layer.closeAll('loading'); //关闭loading

            //请求异常回调
            layer.msg('上传失败',{time:1000,icon: 2});
        }
    });
}

function open_image($this,background) {
    var img = $($this).attr("src");
    //var size = get_image_size(img);

    var imgObj = new Image();                    //新建一个图片对象
    imgObj.src = img;                            //将图片的src属性赋值给新建图片对象的src
    imgObj.onload = function () {
        var size =  new Array(imgObj.width, imgObj.height);
        if(size[0]>1500){
            size[1] = parseInt((1500/size[0]) * size[1]);
            size[0] = 1500;
        }
        if(size[1]>900){
            size[0] = parseInt((900/size[1]) * size[0]);
            size[1] = 900;
        }

        background = background || '#fff';

        //console.log(size);
        layer.open({
            type: 1,
            title: false,
            offset:'auto',
            shadeClose: true,
            area: [size[0]+'px',size[1]+'px'],
            shade:0.3,
            content: '<img src="'+img+'" style="width: '+size[0]+'px; height: '+size[1]+'px;background-color: '+background+'">'
        });
    };

}

function open_video($this) {
    var video = $($this).data("video");
    //console.log(size);
    layer.open({
        type: 1,
        title: false,
        offset:'auto',
        shadeClose: true,
        area: ['500px','800px'],
        shade:0.3,
        content: '<video width="500" height="800" controls autoplay controlsList="nodownload">'+
                    '<source src="'+video+'" type="video/mp4">'+
                    '<object data="'+video+'" width="500" height="800">'+
                    '</object> '+
                '</video>'
    });
}

function open_svga($this,elem) {
    var path = $($this).data("svga");
    //console.log(size);
    layer.open({
        type: 1,
        title: false,
        offset:'auto',
        shadeClose: true,
        area: ['500px','800px'],
        shade:0.3,
        content: '<div class="view_'+elem+'"></div>'
    });

    video_callback(path,'view_'+elem)
}

function video_callback(path,elem) {
    var player = new SVGA.Player('.'+elem);
    player.loops=1;
    player.clearsAfterStop=false;

    var parser = new SVGA.Parser('.'+elem); // 如果你需要支持 IE6+，那么必须把同样的选择器传给 Parser。

    var src = path.replace(oss_domain,'');
    parser.load(svga_domain+src, function(videoItem) {
        player.setVideoItem(videoItem);
        player.startAnimation();
        player.onFinished(function(){
            //console.log("11111")
            //alert("动画停止了！！！哈哈哈@@@")
            //循环播放
            player.startAnimation();
        });
    })

}

function auth_btn_hide(params) {
    $.each(params, function (i,v) {
        if(authdata.indexOf(v)==-1){
            $('.'+v).hide();
        }
    })
}

function get_image_size(url) {
    var i = new Image();                    //新建一个图片对象
    i.src = url;                            //将图片的src属性赋值给新建图片对象的src
    return new Array(i.width, i.height);    //返回图片的长宽像素
}

function load_js(url,callback){
    var script=document.createElement('script');
    script.type="text/javascript";
    if(typeof(callback)!="undefined"){
        if(script.readyState){
            script.onreadystatechange=function(){
                if(script.readyState == "loaded" || script.readyState == "complete"){
                    script.onreadystatechange=null;
                    callback();
                }
            }
        }else{
            script.onload=function(){
                callback();
            }
        }
    }
    script.src=url;
    document.body.appendChild(script);
}

function  compare(attr,rev){
    //第二个参数没有传递 默认升序排列
    if(rev ==  undefined){
        rev = 1;
    }else{
        rev = (rev) ? 1 : -1;
    }

    return function(a,b){
        a = parseInt(a[attr]);
        b = parseInt(b[attr]);
        if(a < b){
            return rev * -1;
        }
        if(a > b){
            return rev * 1;
        }
        return 0;
    }
}

// 存放拖拽的元素
let dragElement = null
function onDragStart(e) {
    // 获取当前拖拽元素
    dragElement = e.currentTarget
}
function onDragOver(e) {
    // 默认的当你dragover的时候会阻止你做drop的操作，所以需要取消这个默认
    e.preventDefault()
}
function onDrop(e,callback,parent) {
    // 当拖动结束的时候，给拖动div所在的位置下面的div做drop事件
    let dropElement = e.currentTarget
    let parentCalss = parent || '.wrapper';

    if (dragElement != null && dragElement != dropElement && $(dragElement).parent().hasClass(parentCalss.substr(1))) {
        let wrapper = document.querySelector(parentCalss)
        // 临时 div 用于存储 box
        let temp = document.createElement('div')
        // 添加 temp 到父元素 wrapper 中
        wrapper.appendChild(temp)
        // 交换
        wrapper.replaceChild(temp, dropElement)
        wrapper.replaceChild(dropElement, dragElement)
        wrapper.replaceChild(dragElement, temp)

        if(typeof callback === "function"){
            callback(parentCalss);
        }
    }
}

function open_photos($this,parent) {
    var images = [];
    var img = $($this).attr('src');
    var index = 0;

    var parentelem = parent ? $(parent) : $($this).parent('div');
    parentelem.find('img').each(function (i,v) {
        if(img==$(v).attr("src")){
            index=i;
        }
        images.push({
            "alt": "",
            "pid": i+1, //图i片id
            "src": $(v).attr("src"), //原图地址
            "thumb": $(v).attr("src") //缩略图地址
        });
    });

    layer.photos({
        photos: {
            "title": "相册预览", //相册标题
            "id": 1, //相册id
            "start": index, //初始显示的图片序号，默认0
            "data": images
        }
        ,anim: 5 //0-6的选择，指定弹出图片动画类型，默认随机
    });
}

function fun_date(num){
    var date1 = new Date(),
        time1=date1.getFullYear()+"-"+(date1.getMonth()+1)+"-"+date1.getDate();//time1表示当前时间
    var date2 = new Date(date1);
    date2.setDate(date1.getDate()+num);
    var time2 = date2.getFullYear()+"-"+(date2.getMonth()+1)+"-"+date2.getDate();

    return time2;
}

function show_tip(elem_class,key) {
    var content = '';
    $.each(tip_message,function (i,v) {
        if(i==key){
            $.each(v,function (ii,vv) {
                if(ii==elem_class){
                    content = vv;
                    return false;
                }
            })
        }
    })

    //小tips
    layer.tips(content, '.'+elem_class, {
        tips: [1, '#3595CC'],
        time: 5000
    });
}

function wangeditor(content) {
    const { createEditor, createToolbar } = window.wangEditor

    var param = {path: 'editor'};
    const editorConfig = {
        placeholder: '请输入内容...',
        onChange(editor) {
            //const html = editor.getHtml()
            //console.log('editor content', html)
            // 也可以同步到 <textarea>
        },
        MENU_CONF:{
            uploadImage: {
                server: '/app/admin/upload/image',
                fieldName:"file",
                maxFileSize: 10 * 1024 * 1024,
                maxNumberOfFiles: 10,
                allowedFileTypes: ['image/*'],
                meta: param,
                metaWithUrl: false,
                headers: get_header(param),
                timeout: 5 * 1000,
                // 单个文件上传成功之后
                onSuccess(file, res) {  // TS 语法
                    // onSuccess(file, res) {          // JS 语法
                    //console.log(`${file.name} 上传成功`, res)
                },
                // 自定义插入图片
                customInsert(res, insertFn) {  // TS 语法
                    // customInsert(res, insertFn) {                  // JS 语法
                    // res 即服务端的返回结果

                    // 从 res 中找到 url alt href ，然后插入图片
                    //console.log(res)
                    insertFn(res.data.url)
                },
            },
            uploadVideo: {
                server: '/app/admin/upload/video',
                fieldName:"file",
                maxFileSize: 50 * 1024 * 1024,
                maxNumberOfFiles: 5,
                allowedFileTypes: ['video/*'],
                meta: param,
                metaWithUrl: false,
                headers: get_header(param),
                timeout: 5 * 1000,
                // 单个文件上传成功之后
                onSuccess(file, res) {  // TS 语法
                    // onSuccess(file, res) {          // JS 语法
                    //console.log(`${file.name} 上传成功`, res)
                },
                // 自定义插入图片
                customInsert(res, insertFn) {  // TS 语法
                    // customInsert(res, insertFn) {                  // JS 语法
                    // res 即服务端的返回结果

                    // 从 res 中找到 url alt href ，然后插入图片
                    //console.log(res)
                    insertFn(res.data.url)
                },
            }

        }
    }


    const editor = createEditor({
        selector: '#editor-container',
        html: '',
        config: editorConfig,
        mode: 'default', // or 'simple'
        schema: {
            // 自定义规则，去掉自动包一层<p>
            rules: [
                {
                    name: 'paragraph',
                    nodes: {
                        allowed: 'inline+'
                    }
                }
            ]
        }
    })

    const toolbarConfig = {}

    const toolbar = createToolbar({
        editor,
        selector: '#toolbar-container',
        config: toolbarConfig,
        mode: 'default', // or 'simple'
    })

    return editor;
}

function getLastYearMonth() {
    var date = new Date();
    let y = date.getFullYear()
    let m = date.getMonth()
    if(m==0){
        y = y-1;
        m = 12;
    }
    return y+'-'+m;
}

function searchWhere(data) {
    let param = {};
    $.each(data,function (i,v) {
        let keyArr = i.match(/\[\w+\]/g);
        if(keyArr!=null){
            let name = i.match(/\w+/)[0];
            let keys = [];
            $.each(keyArr,function (ii,vv) {
                let k = vv.match(/\w+/g)[0];
                keys.push(k);
            })
            if(keys.length==1){
                if(typeof param[name] == "undefined"){
                    param[name] = {};
                }
                param[name][keys[0]] = v;
            }else if(keys.length==2){
                if(typeof param[name] == "undefined"){
                    param[name] = {};
                }
                if(typeof param[name][keys[0]]=="undefined"){
                    param[name][keys[0]] = {};
                }
                param[name][keys[0]][keys[1]] = v;
            }else if(keys.length==3){
                if(typeof param[name] == "undefined"){
                    param[name] = {};
                }
                if(typeof param[name][keys[0]]=="undefined"){
                    param[name][keys[0]] = {};
                }
                if(typeof param[name][keys[0]][keys[1]]=="undefined"){
                    param[name][keys[0]][keys[1]] = {};
                }
                param[name][keys[0]][keys[1]][keys[2]] = v;
            }
        }else{
            param[i] = v;
        }
    })

    return param;
}

function changeSort($this) {
    let id = layui.$($this).data('id');
    let sort = layui.$($this).val();
    let data = {};
    data[PRIMARY_KEY] = id;
    data['sort'] = sort;

    let loading = layer.load();
    layui.$.ajax({
        url: UPDATE_API,
        data: data,
        dataType: "json",
        type: "post",
        async:true,
        headers: get_header(data),
        success: function(res) {
            layer.close(loading);
            if (res.code) {
                return layui.popup.failure(res.msg);
            }
            return layui.popup.success("操作成功", refreshTable);
        }
    })
}

function listen(url) {
    let content = '<div style="margin: 15px"><audio controls autoplay>'+
        '<source src="'+url+'" type="audio/mpeg">'+
        '<object data="'+url+'">'+
        '</object> '+
        '</audio></div>';
    layer.open({
        type: 1,
        title: "试听",
        shade: 0.1,
        maxmin: true,
        area: ["350px","150px"],
        content: content
    });

}

function getChineseLength(str) {
    let length = 0;
    for (let i = 0; i < str.length; i++) {
        if (str.charCodeAt(i) > 255) {
            length += 1;
        }
    }
    return length;
}

function view(param) {
    let content = param ? uncompile(param) : '';

    layer.open({
        type: 1,
        title: "预览",
        shade: 0.1,
        maxmin: true,
        area: ["900px", "520px"],
        content: '<div style="margin: 20px;font-size: 16px;letter-spacing: 2px;">  <textarea disabled rows="23" style="height: 100%;width: 100%">'+content+'</textarea></div>'
    });
}